﻿namespace BusinessFramework
{
    class AttributeRulesExtensionPoint<T> : ExtensionPoint<T>
    {
        public override void Init(ExtensionsOptions<T> options)
        {
            var f = new RuleFactory<T>();

            foreach (var p in ReflectionHelper.GetProperties<T>())
            {
                foreach (PropertyValidationAttribute attribute in p.GetCustomAttributes(typeof(PropertyValidationAttribute), true))
                {
                    attribute.ValidatePropertyUsage(p);

                    var selector = PrecompilationHelper.GetPropertySelector<T>(p);

                    var validation = attribute.GetValidation(p);
                    if (attribute.Message != null)
                        validation.Message = attribute.Message;
                    if (attribute.Severity.HasValue)
                        validation.Severity = attribute.Severity.Value;

                    var rule = f.CreateValidationRuleWithoutDependency(
                        selector, validation)
                        .WithDependencies(p.Name)
                        .WithOwner(p.Name);

                    options.RulePrototypes.Add(rule);
                }
            }
        }
    }
}